package com.socket.client.handler.message.impl;

import cn.hutool.core.util.StrUtil;
import com.socket.client.handler.message.base.BaseMessageHandler;
import com.socket.client.model.base.BaseUser;
import com.socket.client.model.chat.ChatMessage;
import com.socket.client.model.chat.ChatUser;
import com.socket.core.enums.Setting;
import com.socket.core.model.command.enmus.Command;
import com.socket.core.util.Wss;
import org.springframework.stereotype.Component;

/**
 * 用户消息执行器
 */
@Component
public class UserMessageHandler extends BaseMessageHandler {
    protected void parse(ChatMessage message, ChatUser self, BaseUser target) {
        // 禁言状态无法发送消息
        if (authnManager.isMute(self)) {
            self.reject("您已被禁言，请稍后再试", message);
            return;
        }
        // 所有者全员禁言检查
        if (authnManager.getSetting(Setting.ALL_MUTE) && !Wss.isOwner(self.getRole())) {
            self.reject("所有者开启了全员禁言", message);
            return;
        }
        // 检查目标是否存在
        if (target == null) {
            String reason = StrUtil.format("目标{}不存在", message.isGroup() ? "群组" : "用户");
            self.reject(reason, message);
            return;
        }
        // 消息检查
        boolean sensitive = authnManager.getSetting(Setting.SENSITIVE_WORDS);
        if (!authnManager.verifyMessage(self, message, sensitive)) {
            return;
        }
        // 发言标记
        authnManager.operateMark(self);
        ChatUser tuser = target.toUser();
        this.sendTo(self, tuser, message);
        // 保存消息
        boolean isaudio = Command.AUDIO.equals(message.getType());
        boolean read = message.isGroup() || tuser.chooseTarget(self) && !isaudio;
        userManager.cacheRecord(message, !read);
    }

    @Override
    public boolean support(ChatMessage message) {
        return !message.isSysmsg() && !message.isGroup();
    }

    /**
     * 发送消息到目标用户
     */
    void sendTo(ChatUser self, ChatUser target, ChatMessage message) {
        // 你屏蔽了目标
        if (authnManager.shield(self, target)) {
            self.reject("您已屏蔽目标用户", message);
            return;
        }
        // 目标屏蔽了你
        if (authnManager.shield(target, self)) {
            self.reject("消息未送达，您已被目标用户屏蔽", message);
            return;
        }
        // 发送至目标
        target.send(message);
        self.send(message);
    }
}
